<?php
namespace Community\Controller;
use Message\Controller\IndexController;
use Think\Controller;
use User\Model\UserModel;

class ClinicController extends Controller {
    public function _initialize(){
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
    }
    /***
     * 默认护工用字母A表示，康复组用B表示，诊所用C表示
     * 固定创建的社区ID格式为flag+888+id(至少五位数)
     *
     */
/**
 *  创建诊所
 *   parameter：token
 *   return:
 *      'code':
 *      'message':
 *
 */
    public function createClinic(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $time=date('Y-m-d H:i',time());
        $clinicinfo=array(
            'userid'=>$userid,
            'time'=>$time
        );
        if(M('clinic_table')->where(array('userid'=>$userid))->find())
        {
            $result=array(
                'code'=>'-1',
                'message'=>'You had already created!'
            );
            echo json_encode($result);
            return ;
        }
        if(M('clinic_table')->add($clinicinfo))
        {
            $result=array(
                'code'=>'1',
                'message'=>'Create Sucess!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Create Failed!'
            );
        }
        echo json_encode($result);
    }

    /**
     * 编辑诊所服务内容,以及价格，服务区域
     *  parameter：token
     * return:
     *      'code':
     *      'message':
     */
    public function saveServerContent(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $contentInfo=array(
            'content'=>I('content'),
            'prise'=>I('prise'),
            'serverplace'=>I('serverplae'),
        );
        $flag=M('clinic_table')->where(array('userid'=>$userid))->save($contentInfo);
        if($flag)
        {
            $result=array(
                'code'=>'1',
                'message'=>'Add Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Add Failed'
            );
        }
        echo json_encode($result);
    }

    /***
     * 个人申请成为护工
     * parameter:token
     * return:
     *      'code':
     *      'message':
     */
    public function applyPerson(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userdetail=M('userdetail')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $time=date('Y-m-d H:i',time());
        $personinfo=array(
            'userid'=>$userid,
            'time'=>$time,
            'name'=>$userdetail[0]['username']
        );
        if(M('person_table')->where(array('userid'=>$userid))->find())
        {
            $result=array(
                'code'=>'-1',
                'message'=>'You had already apply!'
            );
            echo json_encode($result);
            return ;
        }
        if(M('person_table')->add($personinfo))
        {
            $result=array(
                'code'=>'1',
                'message'=>'Apply Sucess!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Apply Failed!'
            );
        }
        echo json_encode($result);
    }

    /**
     * 编辑护工服务内容,以及价格,服务区域
     *  parameter：token
     * return:
     *      'code':
     *      'message':
     */
    public function savePersonContent(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $contentInfo=array(
            'content'=>I('content'),
            'prise'=>I('prise'),
            'serverplace'=>I('serverplae'),
        );
        $flag=M('person_table')->where(array('userid'=>$userid))->save($contentInfo);
        if($flag)
        {
            $result=array(
                'code'=>'1',
                'message'=>'Add Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Add Failed'
            );
        }
        echo json_encode($result);
    }

    /**
     * 康复小组创建
     * parameter: token
     * return:
     *      'code':
     *      'message':
     */

    public function createGroup(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $member=I('member');//其他成员
        $gname=I('gname');
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $time=date('Y-m-d H:i',time());
        $groupinfo=array(
            'userid'=>$userid,
            'time'=>$time,
            'name'=>$gname
        );
        if(M('group_table')->where(array('userid'=>$userid))->find())//判断数据库中是否有该用户创建的组
        {
            $result=array(
                'code'=>'-1',
                'message'=>'You had already created a group !'
            );
            echo json_encode($result);
            return ;
        }
        $pid=M('group_table')->add($groupinfo);
        if($member!='')
        {
            $arr=explode(',',$member);//获取成员token
            $memberarr=array();
            for ($i=0;$i<count($arr);$i++)
            {
                $val=M('user')->where(array('token'=>$arr[$i]))->select();
                array_push($memberarr,$val[0]['userid']);
                $data=array(
                    'pid'=>$pid,
                    'memberid'=>$memberarr[$i]
                );
                M('member_table')->add($data);//成员表中添加数据
            }
            $member=$i;
        }else
        {
            $member=1;
        }
        M('group_table')->where(array('pid'=>$pid))->save(array('staff'=>$member));
    }

    /***
     * 编辑组的服务内容以及价格，服务区域
     * parameter: token
     * return:
     *      'code':
     *      'message':
     */
    public function saveGroupContent(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $content=I('content');
        $prise=I('prise');
        $serverplace=I('serverplae');

        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $groupInfo=array(
            'content'=>$content,
            'prise'=>$prise,
            'serverplace'=>$serverplace
        );
        $flag=M('person_table')->where(array('userid'=>$userid))->save($groupInfo);
        if($flag)
        {
            $result=array(
                'code'=>'1',
                'message'=>'Add Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Add Failed'
            );
        }
        echo json_encode($result);
    }

    /***
     *
     * 用户评价护工
     * Parameter:token
     *
     */


    /***
     * 关注护工，组员，以及诊所，
     *parameter:token,fakeid
     * return:
     *     'code':
     *     'message':
     */
    public function focusCommunity(){
       $token=I('token');//用户token
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $fakeid=I('fakeid');
        //根据展示的社群id获得值
        if($fakeid=='')
        {
            $result=array(
                'code'=>'-1',
                'message'=>'Please write down you fakeid!'
            );
            echo json_encode($result);
            return;
        }
        $flag=substr($fakeid,0,1);//属于什么身份
        $cid=substr($fakeid,4);
        $userid=M('user')->where(array('token'=>$token))->select();
        $arr=array(
            'userid'=>$userid[0]['userid'],
            'cid'=>$cid
        );
        $map['userid']=$userid[0]['userid'];
        $map['cid']=$cid;
        switch($flag)
        {
            case 'A':
                $info=M('user_person')->where($map)->find();
                break;
            case 'B':
                $info=M('user_group')->where($map)->find();
                break;
            case 'C':
                $info=M('user_clinic')->where($map)->find();
                break;
            default:
                $info=0;
                break;
        }
        if(!$info)
        {
            switch($flag)
            {
                case 'A':
                    M('user_person')->add($arr);
                    $arr=M('person_table')->where(array('id'=>$cid))->select();
                    $arr[0]['fans']++;
                    $data=array(
                        'fans'=>$arr[0]['fans']
                    );
                    M('person_table')->where(array('id'=>$cid))->save($data);
                    break;
                case 'B':
                    M('user_group')->add($arr);
                    $arr=M('group_table')->where(array('id'=>$cid))->select();
                    $arr[0]['fans']++;
                    $data=array(
                        'fans'=>$arr[0]['fans']
                    );
                    M('group_table')->where(array('id'=>$cid))->save($data);
                    break;
                case 'C':
                    M('user_clinic')->add($arr);
                    $arr=M('clinic_table')->where(array('id'=>$cid))->select();
                    $arr[0]['fans']++;
                    $data=array(
                        'fans'=>$arr[0]['fans'],
                    );
                    M('clinic_table')->where(array('id'=>$cid))->save($data);
                    break;
                default :
                    break;
            }
            $result=array(
                'code'=>'1',
                'message'=>'Focus Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Do not focus again!'
            );
        }
        echo json_encode($result);
    }

    /***
     * 显示用户关注的内容，个人，组或者诊所
     * parameter:token，flag,page
     * return:
     *      'fakeid':
     *      'headurl':
     *      'name':
     */
    public function showMyFocus(){
        $token=I('token');
        $flag=I('flag');
        $page=I('page');//page=0的时候加载三个，为其他时候加载所有
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        switch($flag)
        {
            case 'A':
                $community=D('UserRelation')->where(array('userid'=>$userid))->relation('person_table')->select();
                $person=$community[0]['person_table'];//获取护工拥有者的id
                $arr=array();
                for($i=0;$i<count($person);$i++)
                {
                    $data=array(
                        'fakeid'=>'A888'.$community[0]['person_table'][$i]['id'],
                        'headurl'=>$community[0]['person_table'][$i]['headurl'],
                        'name'=>$community[0]['person_table'][$i]['name']
                    );
                    array_push($arr,$data);
                }
                break;
            case 'B':
                // 组
                $community=D('UserRelation')->where(array('userid'=>$userid))->relation('group_table')->select();
                $group=$community[0]['group_table'];
                $arr=array();
                for($i=0;$i<count($group);$i++)
                {
                    $data=array(
                        'fakeid'=>'B888'.$community[0]['group_table'][$i]['id'],
                        'headurl'=>$community[0]['group_table'][$i]['headurl'],
                        'name'=>$community[0]['group_table'][$i]['name']
                    );
                    array_push($arr,$data);
                }
                break;
            case 'C':
                //诊所
                $community=D('UserRelation')->where(array('userid'=>$userid))->relation('clinic_table')->select();
                $clinic=$community[0]['clinic_table'];
                $arr=array();
                for($i=0;$i<count($clinic);$i++)
                {
                    $data=array(
                        'fakeid'=>'C888'.$community[0]['clinic_table'][$i]['id'],
                        'headurl'=>$community[0]['clinic_table'][$i]['headurl'],
                        'name'=>$community[0]['clinic_table'][$i]['name']
                    );
                    array_push($arr,$data);
                }
                break;
        }
        if($page=='0')
        {
            $result=array();
            for($j=0;$j<3;$j++)
            {
                array_push($result,$arr[$j]);
            }
            echo json_encode($result,JSON_UNESCAPED_UNICODE);
        }else{
            echo json_encode($arr,JSON_UNESCAPED_UNICODE);
        }

    }

    /**
     * 用户取消关注的顾问，康复组或者诊所
     * parameter: token,fakeid
     *
     * return: null
     */
    public function cancelMyFocus(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $fakeid=I('fakeid');
        $flag=substr($fakeid,0,1);//属于什么身份
        $cid=substr($fakeid,4);
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $map['userid']=$userid;
        $map['cid']=$cid;
        switch($flag)
        {
            case 'A':
                $code=M('user_person')->where($map)->delete();
                break;
            case 'B':
                $code=M('user_group')->where($map)->delete();
                break;
            case 'C':
                $code=M('user_clinic')->where($map)->delete() ;
                break;
            default:
                break;
        }
        if($code){
            $result=array(
                'code'=>'1',
                'message'=>'Cancel Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Cancel Failed!'
            );
        }
        echo json_encode($result);
    }

    /***
     * 搜索功能
     * Parameter: content
     * return:
     *        "name"
     *        "id"
     */
    public function find(){
        $content=str_replace(" ","",I('content'));//ID类似A8887，第一位代表身份，中间三位不变，后面的才是id
        $flag=substr($content,0,1);//判断是护工、小组、诊所
        $id=(int)substr($content,4);//获取相应的id号
        $idmap['id']=$id;
        $namemap['name']=array('like',"%".$content."%");
        if($content=='')
        {
            return null;
        }
        switch($flag)
        {
            case 'A'://访问个人数据库
                $info= M('person_table')->where($idmap)->select();
                $result=array(
                    'name'=>$info[0]['name'],
                    'id'=>'A888'.$info[0]['id']
                );
                break;
            case 'B'://访问小组数据库
                $info= M('group_table')->where($idmap)->select();
                $result=array(
                    'name'=>$info[0]['name'],
                    'id'=>'B888'.$info[0]['id']
                );
                break;
            case 'C'://访问诊所数据库
                $info= M('clinic_table')->where($idmap)->select();
                $result=array(
                    'name'=>$info[0]['name'],
                    'id'=>'C888'.$info[0]['id']
                );
                break;
            default://三个数据库一起访问搜索对象名字
                $result=array();
                $a=M('person_table')->where($namemap)->select();
                for ($i=0;$i<count($a);$i++)
                {
                    $data=array(
                        'name'=>$a[$i]['name'],
                        'id'=>'A888'.$a[$i]['id']
                    );
                    array_push($result,$data);//把内容添加到数组中
                }
                $c=M('group_table')->where($namemap)->select();
                for ($i=0;$i<count($c);$i++)
                {
                    $data=array(
                        'name'=>$c[$i]['name'],
                        'id'=>'B888'.$c[$i]['id']
                    );
                    array_push($result,$data);//把内容添加到数组中
                }
                $h=M('clinic_table')->where($namemap)->select();
                for ($i=0;$i<count($h);$i++)
                {
                    $data=array(
                        'name'=>$h[$i]['name'],
                        'id'=>'C888'.$h[$i]['id']
                    );
                    array_push($result,$data);//把内容添加到数组中
                }
                break;
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 显示护工，小组，诊所列表页
     * Parameter：flag,page 判断属于护工，保健小组还是诊所,一个page 5条记录
     * Return：
     *      fakeid,
     *      name,
     *      headurl,
     */
    public function showAllCommunity(){
        $flag = I('flag');//A护士  B小组  C诊所   D医院
        $id_head = I('id_head');//地区身份证前位6位
        //如果没传地区标识idhead  默认输出全部
        if(empty($id_head)){
            $where = 1;//构造where为1
        }elseif ($id_head == '500000'){//大重庆范围
            $are_id = M('areaassociation')->where(['flag'=>'C'])->getField('id',true);
            $where = ['are_id'=>['in',$are_id?$are_id:'']];
        }elseif ($id_head == '460000'){//大三亚范围
            $are_id = M('areaassociation')->where(['flag'=>'S'])->getField('id',true);
            $where = ['are_id'=>['in',$are_id?$are_id:'']];
        } else{
            //获取当前地区id
            $are_id = M('areaassociation')->where(['id_head'=>$id_head])->getField('id');
            $where = ['are_id'=>$are_id];
        }
        $p = I('page',1,'intval');//如果为空默认为0，转换成整数
        switch($flag){
            case 'A':
                //根据地区id查出对应的地区的 护士、小组、诊所
                $rows = M('person_table')->distinct(true)->field("id,name,headurl,prise,skill")->join("left join __PERSON_SERVERARE__ ps on __PERSON_TABLE__.id=ps.person_id")->where([$where,'status'=>'1'])->page($p,'5')->select();
                break;
            case 'B':
                $rows = M('group_table')->distinct(true)->field("id,name,headurl,prise,skill")->join("left join __GROUP_SERVERARE__ gs on __GROUP_TABLE__.id=gs.group_id")->where([$where,'status'=>'1'])->page($p,'5')->select();
                break;
            case 'C':
//                $rows = M('clinic_table')->distinct(true)->field("id,name,headurl,prise,skill,serverdetail")->join("left join __CLINIC_SERVERARE__ cs on __CLINIC_TABLE__.id=cs.clinic_id")->where([$where,'status'=>'1'])->page($p,'5')->select();
                $rows = M('clinic_table')->distinct(true)->field("id,big_name,username as name,u.headurl,prise,skill,serverdetail")->join("left join __CLINIC_SERVERARE__ cs on __CLINIC_TABLE__.id=cs.clinic_id")->join('left join __USERDETAIL__ u on u.userid=__CLINIC_TABLE__.userid')->where([$where,'status'=>'1'])->page($p,'5')->select();
                break;
            case 'D':
                $rows = M('hospital_table')->distinct(true)->field("id,name,headurl,skill,serverdetail,phone")->join("left join __HOSPITAL_SERVERARE__ hs on __HOSPITAL_TABLE__.id=hs.hospital_id")->where($where)->page($p,'5')->select();
                break;
        }
        $result=array();
       for($i=0;$i<count($rows);$i++) {
            $info=array(
                'fakeid'=>$flag.'888'.$rows[$i]['id'],
                'name'=>$rows[$i]['name'],
                'big_name'=>$rows[$i]['big_name'] ? $rows[$i]['big_name'] : '',
                'headurl'=>$rows[$i]['headurl'],
                'prise'=>$rows[$i]['prise'] ? $rows[$i]['prise'] : '',
                'skill'=>$rows[$i]['skill'] ? $rows[$i]['skill'] : '',
                'phone'=>$rows[$i]['phone'] ? $rows[$i]['phone'] : '',
                'server_detail'=>$rows[$i]['serverdetail'] ? $rows[$i]['serverdetail'] : '',
            );
            array_push($result,$info);
        }
        echo json_encode($result);
    }

    /***
     * 显示护工或其他身份的详情页
     * parameter:fakeid,takon
     * return:
     *        "name":
     *        "headurl":
     *         "fans":
     *          "place":
     *          "flag" :   //判断关注与否
     *
     */
    public function showCommunityDetail(){
        $fakeid=I('fakeid');
        $token=I('token');
        $flag=substr($fakeid,0,1);//判断是护工、小组、诊所
        $id=(int)substr($fakeid,4);//获取相应的id号
        $user=M('user')->where(array('token'=>$token))->find();
        $map['userid']=$user['userid'];
        $map['cid']=$id;
        switch($flag){
            case 'A':
                $info=M('person_table')->where(array('id'=>$id))->find();
                //获取服务地区
                $server_adress = M('person_serverare')->join("left join __AREAASSOCIATION__ a on a.id=__PERSON_SERVERARE__.are_id")->field('title')->where(['person_id'=>$id])->getField('title',true);
               if(M('user_person')->where($map)->find())
               {
                   $decission='1';
               }else{
                   $decission='0';
               }
                $arr=array(
                    'name'=>$info['name'],
                    'headurl'=>$info['headurl'],
                    'fans'=>$info['fans'],
                    'content'=>$info['content'],
                    'flag'=>$decission,
                    'phone'=>$info['phone'],
                    'wechat'=>$info['wechat'],
                    'serverdetail'=>$info['serverdetail'],
                    'skill'=>$info['skill'],
                    'post'=>$info['post'],
                    'prise'=>$info['prise'],
                    'age'=>$info['age'],
                    'sex'=>$info['sex'],
                    'server_adress'=>$server_adress,
                );
                break;
            case 'B':
                $info=M('group_table')->where(['id'=>$id])->find();
                //获取服务地区
                $server_adress = M('group_serverare')->join("left join __AREAASSOCIATION__ a on a.id=__GROUP_SERVERARE__.are_id")->field('title')->where(['group_id'=>$id])->getField('title',true);
                //判断是否关注
                if(M('user_group')->where($map)->find()) {
                    $decission='1';
                }else{
                    $decission='0';
                }
                //获取小组成员列表
                $doctor_user_ids = M('group_member')->where(['groupid'=>$id])->getField('userid',true);
                $doctors = M('doctor')->where(['user_id'=>['in',$doctor_user_ids],'status'=>1])->select();
//                $doctors = M('doctor')->where(['group_id'=>$id,'status'=>1])->select();
                $member = [];
                foreach ($doctors as $item){
                    $member[] = [
                        'name'=>$item['name'],
                        'headurl'=>$item['headurl'],
                        'id'=>$item['id'],
                    ];
                }
                $evaluate_model = M('evaluate');
                //获取3个小组交易评价
                $evaluates = $evaluate_model->field('id,evaluate,content,create_time,phonenumber')->where(['pid'=>$id,'flag'=>'B'])->join('left join __USER__ u on u.userid=__EVALUATE__.user_id')->order('id desc')->select();
                //获取评论交易次数
                $evaluate_count = $evaluate_model->where(['pid'=>$id,'flag'=>'B'])->count();
                $evaluate = [];
                foreach ($evaluates as $item){
                    $evaluate[] = [
                        'id'=>$item['id'],
                        'phone'=>preg_replace('/(\d{2})\d{7}(\d{2})/','$1***$2',$item['phonenumber']),
                        'content'=>$item['content'],
                        'create_time'=>date('Y-m-d H:i:s',$item['create_time']),
                        'evaluate'=>$item['evaluate'] == '1' ? '不满意' : '满意',
                    ];
                }
                $arr=array(
                    'name'=>$info['name'],
                    'headurl'=>$info['headurl'],
                    'fans'=>$info['fans'],
                    'flag'=>$decission,
                    'phone'=>$info['phone'],
                    'wechat'=>$info['wechat'],
                    'serverdetail'=>$info['serverdetail'],
                    'skill'=>$info['skill'],
                    'post'=>$info['post'],
                    'prise'=>$info['prise'],
                    'server_adress'=>$server_adress,
                    'doctor_member'=>$member,//小组成员数组
                    'group_evaluate'=>$evaluate,//评论数组
                    'group_evaluate_count'=>$evaluate_count,//评论数量
                );
                break;
            case 'C':
                $info=M('clinic_table')->where(['id'=>$id])->find();
                $user_info = M('userdetail')->where(['userid'=>$info['userid']])->find();
                //获取服务地区
//                $server_adress = M('clinic_serverare')->join("left join __AREAASSOCIATION__ a on a.id=__CLINIC_SERVERARE__.are_id")->field('title')->where(['clinic_id'=>$id])->getField('title',true);
                if(M('user_clinic')->where($map)->find())
                {
                    $decission='1';
                }else{
                    $decission='0';
                }
                $arr=array(
//                    'name'=>$info['name'],
                    'name'=>$user_info['username'],
                    'big_name'=>$user_info['big_name'],
//                    'headurl'=>$info['headurl'],
                    'headurl'=>$user_info['headurl'],
                    'fans'=>$info['fans'],
                    'place'=>$info['place'],
                    'flag'=>$decission,
                    'phone'=>$info['phone'],
                    'wechat'=>$info['wechat'],
                    'serverdetail'=>$info['serverdetail'],
                    'skill'=>$info['skill'],
                    'post'=>$info['post'],
                    'prise'=>$info['prise'],
//                    'server_adress'=>$server_adress,
                );
                break;
            case 'D':
                $info=M('hospital_table')->where(array('id'=>$id))->select();
                //获取服务地区
                $server_adress = M('hospital_serverare')->join("left join __AREAASSOCIATION__ a on a.id=__HOSPITAL_SERVERARE__.are_id")->field('title')->where(['hospital_id'=>$id])->getField('title',true);
                if(M('user_hospital')->where($map)->find())
                {
                    $decission='1';
                }else{
                    $decission='0';
                }
                $arr=array(
                    'name'=>$info[0]['name'],
                    'headurl'=>$info[0]['headurl'],
                    'content'=>$info[0]['content'],
                    'fans'=>$info[0]['fans'],
                    'flag'=>$decission,
                    'phone'=>$info[0]['phone'],
                    'wechat'=>$info[0]['wechat'],
                    'serverdetail'=>$info[0]['serverdetail'],
                    'skill'=>$info[0]['skill'],
                    'post'=>$info[0]['post'],
                    'server_adress'=>$server_adress,
                );
                break;
        }
        echo json_encode($arr);

    }

    /**
     * 小组的成员医生详情页
     */
    public function showGroupMemberDetail($id){

    }

    /***
     * 详情页当中发帖
     * parameter：token，fakeid
     * return：
     */
    public function doPost(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $fakeid=I('fakeid');
        $flag=substr($fakeid,0,1);//判断是护工、小组、诊所
        $id=(int)substr($fakeid,4);//获取相应的id号
        switch($flag){
            case 'A':
                $postObject='personpost';
                $info=M('person_table')->where(array('id'=>$id))->select();
                break;
            case 'B':
                $postObject='grouppost';
                $info=M('group_table')->where(array('id'=>$id))->select();
                break;
            case 'C':
                $postObject='clinicpost';
                $info=M('clinic_table')->where(array('id'=>$id))->select();
                break;
        }
        if($userid==$info[0]['userid'])
        {
            $data=array(
                'pid'=>$fakeid,
                'title'=>I('title'),
                'summary'=>I('summary'),
                'content'=>I('content'),
                'postid'=>$flag.md5(time()),//此处有必要需作修改
                'time'=>date('Y-m-d H:i',time())
            );
            M($postObject)->add($data);
            $result=array(
                'code'=>'1',
                'message'=>'Post Success!'
            );

        }else{
            $result=array(
                'code'=>'0',
                'message'=>'No right to post!'
            );
        }
        echo json_encode($result);//发帖成功
    }

    /**
     * 保存御用的订单地址
     *  parameter:token，name，phone，city,fulladress
     *  return :
     *      "code":
     *      "message":
     *
     */
    public function orderAddress(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $name=I('name');
        $phone=I('phone');
        $city=I('city');
        $fulladdress=I('fulladdress');
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $arr=array(
            'name'=>$name,
            'phone'=>$phone,
            'city'=>$city,
            'fulladdress'=>$fulladdress,
            'userid'=>$userid
        );
       if( M('my_userable_address')->add($arr))
       {
           $result=array(
               'code'=>'1',
               'message'=>'Add Success!'
           );
       }else{
           $result=array(
               'code'=>'0',
               'message'=>'Add Failed!'
           );
       }
        echo json_encode($result);
    }

    /**
     * 根据token请求显示用户的地址内容
     * parameter:token
     * return:
     *      "name":
     *      "phone":
     *      "city":
     *      "fulladdress":
     */
    public function showMyAddress(){
        $token=I('token');
        if($token=='')
        {
            echo json_encode($result['code']='3');
            return;
        }
        $user=M('user')->where(array('token'=>$token))->select();
        $userid=$user[0]['userid'];
        $info=M('my_userable_address')->where(array('userid'=>$userid))->select();
        echo json_encode($info,JSON_UNESCAPED_UNICODE);
    }

    /***
     * 社区里面的所有帖子分页进行显示
     * parameter:fakeid,page
     * return:
     *      'postid':
     *      'title':
     *      'summary':
     *      'time':
     */
    public function showPost(){
        $fakeid=I('fakeid');
        $id=(int)substr($fakeid,4);//获取相应的id号
        $identify=substr($fakeid,0,1);//属于什么身份 护工A、小组B、诊所C
        $p=I('page',1,'intval');//如果为空默认为0，转换成整数

        $picFind = M('pic_find');
        //护工A、小组B、诊所C
        switch($identify){
            case 'A':
                //小组
                $result=array();
                $info=M('post')->join('left join __USERDETAIL__ u on __POST__.userid=u.userid')->where(array('pid'=>['like','A%'],'postid'=>$id))->page($p,'5')->field('hd_post.id,hd_post.pid,hd_post.postid,title,summary,hd_post.time,u.headurl,commentcount,u.username')->order('time desc')->select();
                foreach ($info as $k=>$item){
                    //获取图片地址
                    $pic_url = $picFind->where(['post_id'=>$item['id']])->getField('url',true);
                    $arr=array(
                        'fakeid'=>'A'.$item['id'],
                        'title'=>$item['title'],
                        'headurl'=>$item['headurl'],
                        'summary'=>$item['summary'],
                        'postid'=>$item['postid'],
                        'time'=>$item['time'],
                        'username'=>$item['username'],
                        'commentcount'=>$item['commentcount'],
                        'pic'=>$pic_url ? $pic_url : [],
                    );
                    array_push($result,$arr);
                }
                break;
            case 'B':
                //小组
                $result=array();
                $info=M('post')->join('left join __USERDETAIL__ u on __POST__.userid=u.userid')->where(array('pid'=>['like','B%'],'postid'=>$id))->page($p,'5')->field('hd_post.id,hd_post.pid,hd_post.postid,title,summary,hd_post.time,u.headurl,commentcount,u.username')->order('time desc')->select();
                foreach ($info as $k=>$item){
                    //获取图片地址
                    $pic_url = $picFind->where(['post_id'=>$item['id']])->getField('url',true);
                    $arr=array(
                        'fakeid'=>'B'.$item['id'],
                        'title'=>$item['title'],
                        'headurl'=>$item['headurl'],
                        'summary'=>$item['summary'],
                        'postid'=>$item['postid'],
                        'time'=>$item['time'],
                        'username'=>$item['username'],
                        'commentcount'=>$item['commentcount'],
                        'pic'=>$pic_url ? $pic_url : [],
                    );
                    array_push($result,$arr);
                }
                break;
            case 'C':
                //诊所
                $result=array();
                $info=M('post')->join('left join __USERDETAIL__ u on __POST__.userid=u.userid')->where(array('pid'=>['like','C%'],'postid'=>$id))->page($p,'5')->field('hd_post.id,hd_post.pid,hd_post.postid,title,summary,hd_post.time,u.headurl,commentcount,u.username')->order('time desc')->select();
                foreach ($info as $k=>$item){
                    //获取图片地址
                    $pic_url = $picFind->where(['post_id'=>$item['id']])->getField('url',true);
                    $arr=array(
                        'fakeid'=>'C'.$item['id'],
                        'title'=>$item['title'],
                        'headurl'=>$item['headurl'],
                        'summary'=>$item['summary'],
                        'postid'=>$item['postid'],
                        'time'=>$item['time'],
                        'username'=>$item['username'],
                        'commentcount'=>$item['commentcount'],
                        'pic'=>$pic_url ? $pic_url : [],
                    );
                    array_push($result,$arr);
                }
                break;
        }
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /***
     * 给帖子评论
     * parameter：token
     * return:
     *      "code":
     *      "message":
     */
    public function doComment(){
        $token=I('token');
        if($token=='') {
            echo json_encode($result['code']='3');
            return;
        }
        //获取当前帖子id
        $pid = substr(I('postid'),1);
        $content=I('content');
        M('post')->where(array('id'=>$pid))->setInc('commentcount');//更新评论数量
        $user=M('userdetail')->where(array('token'=>$token))->field('username,headurl')->select();
        $arr=array(
            'token'=>$token,
            'content'=>$content,
            'username'=>$user[0]['username'],
            'headurl'=>$user[0]['headurl'],
            'pid'=>$pid,
            'time'=>date('Y-m-d H:s',time())
        );
        $comment_id = M('comment')->add($arr);
        //添加消息到消息表里面
        $post_info = M('post')->where(['id'=>$pid])->find();
        $data = [
            'user_id'=>$post_info['userid'],
            'flag'=>'C',//标识C为评论消息
            'pid'=>$pid,
            'create_time'=>time(),
            'remark'=>$user[0]['username'],
            'content'=>$content,
        ];
        $res = M('news')->add($data);
        if($res){
            //将评论消息推送到发帖者
            $user_token = M('user')->where(['userid'=>$post_info['userid']])->getField('token');
            $message_controller = new IndexController();
            $message_controller->sendPushMessage(md5(date('YmdH',time()).md5('ola')),'有人回复了您的帖子',$user_token);
        }
        if($comment_id) {
            $result=array(
                'code'=>'1',
                'message'=>'Add Success!'
            );
        }else{
            $result=array(
                'code'=>'0',
                'message'=>'Add Failed!'
            );
        }
        echo json_encode($result);
    }


    /***
     * 显示帖子详情加评论内容
     * parameter:id,
     * return:
     *      "content":array("content:")
     *      "comment"=array(
                "username":
                "headurl":
                "content":
     *          "time":
     *      )
     *
     *
     */
    public function showPostDetail(){
        //当前帖子id
        $id = substr(I('id'),1);
        $content = M('post')->where(array('id'=>$id))->select();
        //获取发帖人的名字
        $username = M('userdetail')->where(array('userid'=>$content[0]['userid']))->field('username')->find();
        $comment=M('comment')->where(array('pid'=>$id))->field('username,headurl,content,time')->select();
        //获取帖子图片
        $pic_url = M('pic_find')->where(array('post_id'=>$id))->getField('url',true);
        $info=array();
        for($i=0;$i<count($comment);$i++){
            $data=array(
                'username'=>$comment[$i]['username'],
                'headurl'=>$comment[$i]['headurl'],
                'content'=>$comment[$i]['content'],
                'time'=>$comment[$i]['time']
            );
            array_push($info,$data);
        }
        $result=array(
            'content'=>$content,
            'username'=>$username,
            'comment'=>$info,
            'pic'=>$pic_url ? $pic_url : [] ,
        );
        echo json_encode($result,JSON_UNESCAPED_UNICODE);
    }

    /**
     * 判断当前用户是否存属于诊所
     * parameter：token   //当前用户token
     * parameter：fakeid   //当前诊所或者小组id字符  当前诊所flag护工用字母A表示，康复组用B表示，诊所用C表示
     * return:
     *      "code":
     *      "message":
     */
    public function findDecide(){
        //获取当前诊所或小组id
        $gorcid = (int)substr(I('fakeid'),4);
        //属于什么模块
        $flag = substr(I('fakeid'),0,1);
        $token=I('token');
        if($token=='') {
            echo json_encode($result['code']='3');
            return;
        }
        //获取当前用户信息
        $user = M('userdetail')->where(array('token'=>$token))->find();
        switch ($flag){
            case 'A':
                $res = M('person_member')->where(['userid'=>$user['userid'],'personid'=>$gorcid])->find();
                //如果当前用户不在小组内，将不能发帖
                if(!$res){
                    $result = array(
                        'code'=>'0',
                        'message'=>'No right to post!'
                    );
                    echo json_encode($result);//验证失败
                    exit;
                }
                break;
            case 'B':
                $res = M('group_member')->where(['userid'=>$user['userid'],'groupid'=>$gorcid])->find();
                //如果当前用户不在小组内，将不能发帖
                if(!$res){
                    $result = array(
                        'code'=>'0',
                        'message'=>'No right to post!'
                    );
                    echo json_encode($result);//验证失败
                    exit;
                }
                break;
            case 'C':
                $res = M('clinic_member')->where(['userid'=>$user['userid'],'clinicid'=>$gorcid])->find();
                //如果当前用户不在诊所内，将不能发帖
                if(!$res){
                    $result = array(
                        'code'=>'0',
                        'message'=>'No right to post!'
                    );
                    echo json_encode($result);//验证失败
                    exit;
                }
                break;
        }
        echo json_encode(['code'=>1]);//验证成功
    }

    /**
     * 执行发现中诊所帖子图片上传
     * Parameter：name,  //判断属于地区社群还是兴趣社群
     * Parameter：fakeid,  //当前诊所或者小组id字符  当前诊所flag护工用字母A表示，康复组用B表示，诊所用C表示
     * return :id,返回上传成功的id编号
     */
    public function uploadPictureToFind(){
        $pictureName=I('name');
        $fakeid = I('fakeid');
        //属于什么模块
        $flag = substr($fakeid,0,1);
        $url = upload($pictureName,'find/'.$flag);//获取存入的地址
        //如果图片没有上传成功直接返回
        if (empty($url)){
            $result = [
                'id'=>'',
                'status'=>0,
            ];
            echo json_encode($result);
            exit;
        }
        //构建入库数据
        $data = array(
            'url'=>$url,
            'flag'=>$flag
        );
        //将地址存入相应的表格中
        $id = M('pic_find')->add($data);
        $result = [
            'id'=>$id ? $id : '',
            'status'=>$id ? 1 : 0,
        ];
        $this->ajaxReturn($result);
    }

    /**
     * 发现模块的发帖
     * 只允许当前对应的诊所成员才能发帖
     * parameter：token   //当前用户token
     * parameter：fakeid   //当前诊所或者小组id字符  当前诊所flag护工用字母A表示，康复组用B表示，诊所用C表示
     * parameter：title   //标题
     * parameter：content   //内容
     * return:
     *      "code":
     *      "message":
     */
    public function findToPost(){
        $fakeid = I('fakeid');
        $pic=I('pic');//图片数组
        //获取当前诊所或小组id
        $gorcid=(int)substr($fakeid,4);
        //属于什么模块
        $flag = substr($fakeid,0,1);
        $title = I('title');
        //如果标题为空直接返回
        if(empty($title) || empty(I('content'))){
            $result=array(
                'code'=>'0',
                'message'=>'error',
            );
            echo json_encode($result);//发帖失败
            exit;
        }
        //调用发帖
        $result = $this->_findPost($gorcid,$flag,$pic);
        //将诊所或者小组表中的帖子数post+1
        switch ($flag){
            case 'A':
                M('person_table')->where(['id'=>$gorcid])->setInc('post');
                break;
            case 'B':
                M('group_table')->where(['id'=>$gorcid])->setInc('post');
                break;
            case 'C':
                M('clinic_table')->where(['id'=>$gorcid])->setInc('post');
                break;
        }
        $this->ajaxReturn($result);//发帖成功
    }

    /**
     * 发帖共用代码
     * @param $gorcid
     * @param $flag
     * @return array|void
     */
    private function _findPost($gorcid,$flag,$pic) {
        $token=I('token');
        if($token=='') {
            echo json_encode($result['code']='3');
            return;
        }
        $user = M('userdetail')->where(array('token'=>$token))->find();
        $table = '';
        $ident = '';
        if($flag == 'B'){
            //小组贴
            $table = 'group_member';
            $ident = 'groupid';
        }elseif($flag == 'C'){
            //诊所贴
            $table = 'clinic_member';
            $ident = 'clinicid';
        }elseif($flag == 'A'){
            //诊所贴
            $table = 'person_member';
            $ident = 'personid';
        }
        $res = M($table)->where(['userid'=>$user['userid'],$ident=>$gorcid])->find();
        //如果当前用户不在诊所内，将不能发帖
        if(!$res){
            $result = array(
                'code'=>'0',
                'message'=>'No right to post!'
            );
            echo json_encode($result);//发帖失败
            exit;
        }
        //构建入库数据
        $data=array(
            'pid'=>$flag .'888' . $gorcid,
            'title'=>I('title'),
            'summary'=>substr(I('content'),0,15),
            'content'=>I('content'),
            'time'=>date('Y-m-d H:i:s',time()),
            'postid'=>$gorcid,
            'userid'=>$user['userid'],
            'headurl'=>$user['headurl'],
        );
        $post_id = M('post')->add($data);
        //创建图片关联表pic_find数据
        $pic_find = M('pic_find');
        foreach ($pic as $item){
            $pic_find->where(['id'=>$item])->save(['post_id'=>$post_id]);
        }
        return array(
            'code'=>$res ? '1' : '0',
            'message'=>$res ? 'Success' : 'error',
            'post_id'=>$post_id,
        );
    }

    /**
     * 删帖
     * @param $id 帖子id
     * @param $token 当前用户token
     * @return array 返回删除返回信息
     */
    public function deleteFind($id,$token){
        //根据token获取当前用户的id
        $user_model = new UserModel();
        $user_id = $user_model->getIdByToken($token);
        //获当当前贴子的发帖人  判断当前登录的人是否能删
        $post_user_id = M('post')->where(['id'=>$id])->getField('userid');
        if($post_user_id != $user_id){
            $this->ajaxReturn(['code'=>0]);
            exit;
        }
        //删除对应pic_post的图片表
        M('pic_find')->where(['post_id'=>$id])->delete();
        //删除评论
        M('comment')->where(['pid'=>$id])->delete();
        //根据id查询出属于哪个分类 将父级表的帖子统计-1
        $flag = M('post')->where(['id'=>$id])->field('postid,pid')->find();
        $pid = substr($flag['pid'],0,1);
        switch ($pid){
            case 'A':
                //将地区或者兴趣表的帖子统计-1
                M('person_table')->where(['id'=>$flag['postid']])->setDec('post');
                break;
            case 'B':
                //将地区或者兴趣表的帖子统计-1
                M('group_table')->where(['id'=>$flag['postid']])->setDec('post');
                break;
            case 'C':
                //将地区或者兴趣表的帖子统计-1
                M('clinic_table')->where(['id'=>$flag['postid']])->setDec('post');
                break;
        }
        $res = [];
        if(M('post')->where(['id'=>$id])->delete()){
            $res = ['code'=>1];
        }else{
            $res = ['code'=>0];
        }
        $this->ajaxReturn($res);
    }


    /**
     * 前台搜索
     * @param $keyword  获取搜索内容keyword
     * @param $flag  获取标识flag，A护工 B小组 C诊所 D地区社群 E兴趣社群 F医院
     * @param $are_flag 地区标识  C重庆  S三亚
     * return: json
     */
    public function homeSearch($keyword,$flag,$are_flag){
        //获取当前地区id
        $are_ids = M('areaassociation')->where(['flag'=>$are_flag])->getField('id',true);
        $data = [];
        $p=I('page',1,'intval');//如果为空默认为0，转换成整数
        switch ($flag){
            case 'A':
                //获取当前搜索地区的护工
                $person_ids = M('person_serverare')->distinct(true)->where(['are_id'=>['in',$are_ids]])->getField('person_id',true);
                $where['name']  = ['like', '%'. $keyword .'%'];
                $where['skill']  = ['like','%'. $keyword .'%'];
                $where['_logic'] = 'or';
                $data = M('person_table')->page($p,'5')->where([$where,'id'=>['in',$person_ids ? $person_ids : '']])->select();
                break;
            case 'B':
                $group_ids = M('group_serverare')->distinct(true)->where(['are_id'=>['in',$are_ids]])->getField('group_id',true);
                $where['name']  = array('like', '%'. $keyword .'%');
                $where['skill']  = array('like','%'. $keyword .'%');
                $where['_logic'] = 'or';
                $data = M('group_table')->page($p,'5')->where([$where,'id'=>['in',$group_ids ? $group_ids : '']])->select();
                break;
            case 'C':
                $clinic_ids = M('clinic_serverare')->distinct(true)->where(['are_id'=>['in',$are_ids]])->getField('clinic_id',true);
                $where['name']  = array('like', '%'. $keyword .'%');
                $where['skill']  = array('like','%'. $keyword .'%');
                $where['_logic'] = 'or';
                $data = M('clinic_table')->page($p,'5')->where([$where,'id'=>['in',$clinic_ids ? $clinic_ids : '']])->select();
                break;
            case 'D':
                $data = M('areapost')->page($p,'5')->where(['title'=>['like','%'.$keyword.'%']])->select();
                break;
            case 'E':
                $data = M('interestpost')->page($p,'5')->where(['title'=>['like','%'.$keyword.'%']])->select();
                break;
            case 'F':
                $clinic_ids = M('hospital_serverare')->distinct(true)->where(['are_id'=>['in',$are_ids]])->getField('hospital_id',true);
                $where['name']  = array('like', '%'. $keyword .'%');
//                $where['skill']  = array('like','%'. $keyword .'%');
                $where['_logic'] = 'or';
                $data = M('hospital_table')->page($p,'5')->where([$where,'id'=>['in',$clinic_ids ? $clinic_ids : '']])->select();
                break;
        }
        $this->ajaxReturn($data);
    }

    /**
     * 社群
     * 前台banner跳转到指定帖子显示指定的名字
     * 根据标识flag获取对应的地区或兴趣名称
     * @param $flag //标识+id，标识A地区B社群，id为帖子id
     */
    public function getAreByid($flag){
        //获取标识和对应帖子id
        $identifying = substr($flag,0,1);
        $id = substr($flag,1);
        $name = [];
        switch ($identifying){
            case 'A'://地区贴
                //获取对应的pid
                $pid = M('areapost')->field('pid')->where(['id'=>$id])->find();
                //根据pid获取地区的名称
                $name = M('areaassociation')->field('title')->where(['id'=>$pid['pid']])->find();
                break;
            case 'B'://兴趣贴
                //获取对应的pid
                $pid = M('interestpost')->field('pid')->where(['id'=>$id])->find();
                //根据pid获取兴趣的名称
                $name = M('interestassociation')->field('title')->where(['id'=>$pid['pid']])->find();
                break;
        }
        $this->ajaxReturn(['name'=>$name['title']]);
    }
    /**
     * 发现
     * 前台banner跳转到指定帖子显示指定的名字
     * 根据标识flag获取对应的护工、小组、诊所名称
     * @param $flag //标识+id，标识A护工B小组C诊所，id为帖子id
     */
    public function getFindNameByid($flag){
        //获取标识和对应帖子id
        $identifying = substr($flag,0,1);
        $id = substr($flag,1);
        $name = [];
        switch ($identifying){
            case 'A'://护工贴
                //获取对应的pid
                $pid = M('post')->field('postid')->where(['id'=>$id])->find();
                //根据pid获取护工的名称
                $name = M('person_table')->field('name')->where(['id'=>$pid['postid']])->find();
                break;
            case 'B'://小组贴
                $pid = M('post')->field('postid')->where(['id'=>$id])->find();
                $name = M('group_table')->field('name')->where(['id'=>$pid['postid']])->find();
                break;
            case 'C'://诊所贴
                $pid = M('post')->field('postid')->where(['id'=>$id])->find();
                $name = M('clinic_table')->field('name')->where(['id'=>$pid['postid']])->find();
                break;
        }
        echo json_encode(['name'=>$name['name']],JSON_UNESCAPED_UNICODE);
    }


}
